<template>
  <div class="mod-prod-effect">
    <!-- 数据 -->
    <!-- 实时概况板块 -->
    <div class="realtime-situation">
      <!-- 栏目标题行 -->
      <div class="new-page-title">
        <!-- 左边 -->
        <div class="title-left">
          <p class="line" />
          <span class="text">{{ $t("menuList.commodityInsight") }}</span>
        </div>
        <div class="title-right">
          <el-input
            v-model="prodName"
            style="width: 290px;"
            :placeholder="$t('dataAnaly.pleasToSearch')"
            clearable
            @keyup.enter="onSearch"
          >
            <template #suffix>
              <el-icon @click="onSearch">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>
      <!-- /栏目标题行 -->
      <div />
      <!-- 商品概况列表 -->
      <div class="item-list">
        <el-form
          :inline="true"
          :model="dataForm"
          @submit.prevent
        >
          <el-form-item :label="$t('product.status') + ':'">
            <el-select
              v-model="dataForm.status"
              style="width:100px;"
              :placeholder="$t('dataAnaly.activityArea')"
              @change="onChangeDataForm()"
            >
              <el-option
                :label="$t('dataAnaly.allStatus')"
                :value="0"
              />
              <el-option
                :label="$t('dataAnaly.onSale')"
                :value="1"
              />
              <el-option
                :label="$t('dataAnaly.inTheWarehouse')"
                :value="2"
              />
              <el-option
                :label="$t('dataAnaly.soldOut')"
                :value="3"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div class="title-right">
              <el-select
                v-model="dateValue"
                style="width:120px;"
                @change="onSetDateRange(dateValue)"
              >
                <el-option
                  v-for="item in dateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <span
                v-if="dateValue === 1"
                class="title-time"
              >{{ nowDate }}</span>
              <div
                v-if="dateValue === 1"
                class="default-btn text-btn"
                @click="onFlushDateTime"
              >
                {{ $t("admin.refresh") }}
              </div>
              <span
                v-if="dateValue === 2 || dateValue === 3"
                class="title-time"
              >{{ dateRange[0] }}{{ $t("time.tip") }}{{ dateRange[1] }}</span>
            </div>
            <div class="title-picker">
              <el-date-picker
                v-if="dateValue === 4 "
                v-model="dateRange[0]"
                style="width: 150px;"
                type="date"
                :placeholder="$t('admin.seleData')"
                :picker-options="PickerOptions"
                @change="onHandleRangeFour()"
              />
            </div>
            <div class="title-picker">
              <el-date-picker
                v-if="dateValue === 5 "
                v-model="preMonth"
                style="width: 150px;"
                type="month"
                :placeholder="$t('dataAnaly.selectMonth')"
                :picker-options="monthPickerOptions"
                @change="onHandleMonth"
              />
            </div>
          </el-form-item>
        </el-form>
        <el-form
          :model="form"
          @submit.prevent
        >
          <el-form-item :label="$t('dataAnaly.salesIndex')">
            <el-checkbox-group v-model="form.saleIndex">
              <el-checkbox
                :label="$t('dataAnaly.impressions')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.exposure')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.numberOfAdditionalPurchases')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.numberOfCases')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.placeOrderPerson')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.payers')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.placeOrderNum')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.numberOfGoodsPaid')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.placeOrderAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.commodityPaymentAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.singleProductConversionRate')"
                name="saleIndex"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item :label="$t('dataAnaly.serviceIndex')">
            <el-checkbox-group v-model="form.serviceIndex">
              <el-checkbox
                :label="$t('dataAnaly.numberOfOrdersRequestedForRefund')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.numberOfPeopleApplyingForRefund')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.numberOfSuccessfullyRefundedOrders')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.numberOfSuccessfulRefunds')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.successfulRefundAmount')"
                name="saleIndex"
              />
              <el-checkbox
                :label="$t('dataAnaly.refundRate')"
                name="saleIndex"
              />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item
            :label="$t('dataAnaly.serviceIndex')"
            class="transparent-text"
          >
            <div
              id="maxSelectSpan"
              class="select-txt"
              style="color: #155BD4;"
            >
              {{ $t("dataAnaly.chooseUpTo8Items") }}
            </div>
            <div class="select-txt">
              {{ $t("dataAnaly.chosen") }} <span class="select-num-txt">{{ selectNum }}</span>/8 {{ $t("dataAnaly.indicators") }}
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- /商品概况列表 -->
      <!-- 说明文字板块 -->
      <div class="title-text-info">
        <div>{{ $t("dataAnaly.orderTip3") }}{{ $t("dataAnaly.orderTip4") }}</div>
        <div>{{ $t("dataAnaly.orderTip5") }}</div>
      </div>
      <!-- /说明文字板块 -->
      <div class="prod-hid-txt">
        {{ $t("dataAnaly.prodHid") }}
      </div>
    </div>
    <!-- /实时概况板块 -->

    <!-- 整体看板 -->
    <div class="whole-plate">
      <!-- 图表 -->
      <prod-effect-table
        :prod-data="prodData"
        style="width: 100%; margin-bottom: 20px"
      />
      <!-- /图表 -->
      <!-- 分页 -->
      <el-pagination
        v-if="prodData.data.length"
        :current-page="page.pageIndex"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange "
      />
      <!-- /分页 -->
    </div>
    <!-- /整体看板 -->
  </div>
</template>

<script setup>
import ProdEffectTable from '../prod-effect-table/index.vue'
import Big from 'big.js'
import moment from 'moment'

const prodData = reactive({
  prodName: null, // 商品名称
  dateValue: null, // 时间的选择
  dateRange1: null, // 时间区间
  dataForm: {
    group: null,
    status: null
  }, // 筛选信息
  form: {
    saleIndex: [''], // 销售指标
    serviceIndex: [''] // 服务指标
  }, // 指标选择信息
  sumData: [], // 所有指标
  data: [], // 数据
  params: {
    shopId: null,
    dateType: 1,
    group: 0,
    status: 0,
    prodName: null,
    startTime: null,
    endTime: null
  }
}) // 商品 概况列表
const PickerOptions = reactive({
  disabledDate (time) {
    const date = moment().add(-1, 'days').startOf('day')
    return (
      time.getTime() > date.valueOf()
    )
  }
})
const monthPickerOptions = reactive({
  disabledDate (time) {
    const month1 = moment().startOf('month')
    return (
      time.getTime() > month1.valueOf()
    )
  }
})
const dateOptions = [
  {
    label: $t('dataAnaly.realTimeToday'),
    value: 1
  },
  {
    label: $t('dataAnaly.nearly7Days'),
    value: 2
  },
  {
    label: $t('dataAnaly.nearly30Days'),
    value: 3
  },
  {
    label: $t('dataAnaly.natureDay'),
    value: 4
  },
  {
    label: $t('dataAnaly.naturalMoon'),
    value: 5
  }
]

const form = reactive({
  saleIndex: [], // 销售指标
  serviceIndex: [] // 服务指标
})
const selectNum = ref(0) // 选择指标的数量
let sumData = []
watch(() => form.saleIndex, () => {
  selectNum.value = form.serviceIndex.length + form.saleIndex.length
  prodData.form = form
  sumData = []
  sumData = sumData.concat(form.serviceIndex).concat(form.saleIndex)
  prodData.sumData = sumData
  const checks = document.getElementsByName('saleIndex')
  const span = document.getElementById('maxSelectSpan')
  checks.forEach(i => {
    if (selectNum.value >= 8) {
      textShare(span, 'red')
      if (!i.checked) {
        i.setAttribute('disabled', 'true')
      }
    }
  })
  if (selectNum.value < 8) {
    textShare(span, 'black')
    checks.forEach(i => {
      i.removeAttribute('disabled')
    })
  }
})
watch(() => form.serviceIndex, () => {
  selectNum.value = form.saleIndex.length + form.serviceIndex.length
  prodData.form = form
  sumData = []
  sumData = sumData.concat(form.serviceIndex).concat(form.saleIndex)
  prodData.sumData = sumData
  const checks = document.getElementsByName('saleIndex')
  const span = document.getElementById('maxSelectSpan')
  checks.forEach(i => {
    if (selectNum.value >= 8) {
      textShare(span, 'red')
      if (!i.checked) {
        i.setAttribute('disabled', 'true')
      }
    }
  })
  if (selectNum.value < 8) {
    textShare(span, 'black')
    checks.forEach(i => {
      i.removeAttribute('disabled')
    })
  }
})
onMounted(() => {
  onSetDateRange(2)
  // 初始选择3个默认数据项
  form.saleIndex = [
    $t('dataAnaly.impressions'),
    $t('dataAnaly.exposure')
  ]
  form.serviceIndex = [
    $t('dataAnaly.numberOfOrdersRequestedForRefund')
  ]
})
/**
 * 刷新时间
 */
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const nowDate = ref(null)
let dateRange1 = [] // 商品整体概况的时间选择范围
const onFlushDateTime = () => {
  const date = moment()
  nowDate.value = moment(date).format('YYYY-MM-DD HH:mm:ss')
  dateRange1 = [moment(date).startOf('days').format('LL'), nowDate.value]
  prodData.dateRange1 = dateRange1
  onGetProdEffect(page)
}
/**
 * 1:今天 2: 近七天 3:近30天 4:昨天 5:自然月(前一个月如当前月为7月，自然月为6月)
 */
const dateValue = ref(2)
const dateRange = ref([])
const preMonth = ref('') // 前一个月
const onSetDateRange = (val) => {
  let startDay = null
  let endDay = null
  prodData.dateValue = val
  if (val === 1) {
    startDay = 0
    endDay = 0
    dateRange1 = [moment().startOf('days').format('LL'), nowDate.value]
    prodData.dateRange1 = dateRange1
    const date = moment()
    nowDate.value = moment(date).format('YYYY-MM-DD HH:mm:ss')
    onGetProdEffect(page)
    return
  } else if (val === 2) {
    startDay = -7
    endDay = -1
  } else if (val === 3) {
    startDay = -30
    endDay = -1
  } else if (val === 4) {
    startDay = 0
    endDay = 0
  } else if (val === 5) {
    preMonth.value = onGetPreMonth()
    return
  } else {
    return
  }
  // 开始时间
  const startTime = moment().add(startDay, 'days')
  // 结束时间
  const endTime = moment().add(endDay, 'days')
  dateRange.value = [startTime.format('L'), endTime.format('L')]
  dateRange1 = [startTime.startOf('days').format('LL'), endTime.endOf('days').format('LL')]
  prodData.dateRange1 = dateRange1
  onGetProdEffect(page)
}
/**
 * 获取前一个月的时间
 */
const onGetPreMonth = (date) => {
  if (!date) {
    date = new Date()
  }
  // 月的开始时间
  const timeStar = moment(date).startOf('month')
  // 月的结束时间
  const timeEnd = moment(timeStar).endOf('month')
  dateRange1 = [timeStar.format('LL'), timeEnd.format('LL')]
  prodData.dateRange1 = dateRange1
  onGetProdEffect(page)
  return moment(date).format('L')
}
/**
 * 当dateRange == 4 监听dateRange[0]的变化
 */
const onHandleRangeFour = () => {
  const date = dateRange.value[0]
  if (date) {
    const d = moment(date).startOf('days')
    dateRange1 = [d.format('LL'), moment(d).endOf('days').format('LL')]
    prodData.dateRange1 = dateRange1
  } else {
    dateRange1 = ['1971-01-01 00:00:00', '1971-01-01 00:00:00']
    prodData.dateRange1 = dateRange1
  }
  onGetProdEffect(page)
}
/**
 * 当dateRange == 5 监听dateRange[0]的变化
 */
const onHandleMonth = () => {
  if (preMonth.value) {
    onGetPreMonth(preMonth.value)
  } else {
    dateRange1 = ['1971-01-01 00:00:00', '1971-01-01 00:00:00']
    onGetProdEffect(page)
  }
}
/**
 * 获取商品概况数据
 */
const dataForm = reactive({
  group: 0,
  status: 0
})
const prodName = ref(null)
const onGetProdEffect = (pageParam) => {
  // 请求参数传给表格子组件
  const params = {}
  params.shopId = null
  params.dateType = dateValue.value
  params.group = dataForm.group
  params.status = dataForm.status
  params.prodName = prodName.value
  params.startTime = dateRange1[0]
  params.endTime = dateRange1[1]
  prodData.params = params
  http({
    url: http.adornUrl('/multishop/prodAnalysis/getProdEffect'),
    method: 'get',
    params: http.adornParams(
      {
        current: pageParam == null ? page.currentPage : pageParam.currentPage,
        size: pageParam == null ? page.pageSize : pageParam.pageSize,
        shopId: null,
        dateType: dateValue.value,
        group: dataForm.group,
        status: dataForm.status,
        prodName: prodName.value,
        startTime: dateRange1[0],
        endTime: dateRange1[1]
      }
    )
  }).then(({ data }) => {
    prodData.data = data.records
    if (data) {
      data.records.forEach(element => {
        if (element.singleProdRate > 0) {
          Big.DP = 2
          element.singleProdRate = new Big(element.singleProdRate).times(100).toFixed()
          element.refundSuccessRate = new Big(element.refundSuccessRate).times(100).toFixed()
        }
      })
      prodData.data = data.records
      page.total = data.total
    }
  })
}
/**
   * 搜索商品名称
   */
const onSearch = () => {
  onGetProdEffect(page)
}
// 每页数
const onPageSizeChange = (val) => {
  page.pageSize = val
  page.currentPage = 1
  onGetProdEffect(page)
}
// 当前页
const onPageChange = (val) => {
  page.currentPage = val
  onGetProdEffect(page)
}
/**
   * 选择框改变
   */
const onChangeDataForm = () => {
  prodData.dataForm = dataForm
  onGetProdEffect(page)
}
/**
   * 文字效果
   */
const textShare = (div, color) => {
  div.style.color = color
}

</script>

<style lang="scss" scoped>

  .mod-prod-effect {
    .item-list {
      background: #f7f8fa;
      margin-bottom: 20px;
      padding: 25px 20px;
      :deep(.el-form) {
        .el-form-item.el-form-item--mini {
          margin-bottom: 14px;
        }
        .el-form-item.el-form-item--mini.transparent-text {
          margin-bottom: 0;
        }
        .transparent-text ::v-deep(.el-form-item__label) {
          color: transparent;
        }
      }
    }
    .title-text-info {
      background: rgba(246, 192, 35, 0.06);
      border: 1px solid #F6C023;
      padding: 18px;
    }
    .title-text-info div {
      font-size: 12px;
      line-height: 18px;
      color: #666;
      &:first-child {
        margin-bottom: 12px;
      }
    }
    .select-txt:first-child {
      color: #155bd4;
    }
    .select-txt {
      font-size: 12px;
      color: #999999;
      display: inline-block;
    }
    .select-num-txt {
      color: #155BD4;
    }
    .prod-hid-txt {
      margin-top: 25px;
      font-size: 12px;
      color: #666666;
    }
    .title-left {
      text-align: left;
      display: flex;
      align-items: center;
      width: 80%;
    }
    .title-right {
      text-align: right;
      display: inline;
      // width: 20%;
      .default-btn.text-btn {
        font-size: 12px;
      }
    }
    .title-picker {
      display: inline;
    }
    .title-time {
      color: #666666;
      font-size: 12px;
      vertical-align: middle;
      padding: 0 12px;
    }

    /**
    整体看板
     */
    .whole-plate {
      margin: 15px 0 30px;
    }
  }
</style>
